package jeye.servlet.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jeye.Defaults;
import jeye.dao.EventDAO;
import jeye.utils.ImageUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class FrameAction implements ServletAction {

	private static final String HEIGHT_PARAM = "height";

	private static final String WIDTH_PARAM = "width";

	private static final String ID_PARAM = "id";

	private static final String QUALITY_PARAM = "quality";
	
	@Autowired
	private EventDAO eventDAO;

	public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String frameid = request.getParameter(ID_PARAM);
		String widthStr = request.getParameter(WIDTH_PARAM);
		String heightStr = request.getParameter(HEIGHT_PARAM);
		String qualityStr = request.getParameter(QUALITY_PARAM);
		
		if(StringUtils.isNumeric(frameid)) {
			byte[] frame = eventDAO.getFrame(Long.valueOf(frameid)).getFrame();
			
			if(StringUtils.isNumeric(widthStr) && StringUtils.isNumeric(heightStr)) {
				ByteArrayInputStream bais = new ByteArrayInputStream(frame);
				BufferedImage image = ImageIO.read(bais);
				int width = Integer.valueOf(widthStr);
				int height = Integer.valueOf(heightStr);
				
				image = ImageUtils.resizeImage(image, width, height);
				
				float quality = Defaults.SERVICE_QUALITY;
				
				if(StringUtils.isNotBlank(qualityStr)) {
					try {
						quality = Float.valueOf(qualityStr);
					}catch(NumberFormatException e) {
						quality = Defaults.SERVICE_QUALITY;
					}
				}

				frame = ImageUtils.getBytesFromImage(image, quality);
			}
			
			response.getOutputStream().write(frame);
		}
	}
	
}
